<?php
hd_core::load_class('init', 'admin');
class member_control extends init_control {
    public function _initialize() {
        parent::_initialize();
        $this->service = $this->load->service('member/member');
        $this->scoreService = $this->load->service('member/scoring');
        $this->service_student = $this->load->service('member/member_student');
        $this->attachment_service = $this->load->service('attachment/attachment');
        $this->pointService = $this->load->service('member/point');
        helper('attachment');
    }

    public function index() {
        $sqlmap = array();
        $sqlmap['username|email|mobile'] = array("LIKE", '%'.$_GET['keyword'].'%');
        $sqlmap['group_id'] = 1;
		if($_GET['status'] > 1){
			if($_GET['status'] == 2){
				$sqlmap['mobilestatus'] = 0;
			}elseif($_GET['status'] == 3){
				$mids = model('member_deposit')->getField('mid',TRUE);
				$sqlmap['id'] = array("NOT IN",$mids);
				$sqlmap['mobilestatus'] = 1;
			}elseif($_GET['status'] == 4){
				$mids = model('member_student')->where(array('class_id'=>array('eq',0),'end_time'=>0))->getField('mid',TRUE);
				$mids1 = model('member_student')->where(array('class_id'=>array('gt',0),'end_time'=>array('gt',time())))->getField('mid',TRUE);
				$mids0 = array();
				foreach($mids as $v){
					if(!in_array($v,$mids1)){
						$mids0[] = $v;
					}
				}
				$sqlmap['id'] = array("IN",$mids0);
			}elseif($_GET['status'] == 5){
				$mids = model('member_student')->where(array('class_id'=>array('gt',0),'end_time'=>array('gt',time())))->getField('mid',TRUE);
				$mids1 = model('member_student')->where(array('class_id'=>array('eq',0),'end_time'=>0))->getField('mid',TRUE);
				$mids0 = array_merge($mids,$mids1);				
				$mids = model('member_deposit')->getField('mid',TRUE);				
				$mids2 = array();
				foreach($mids as $v){
					if(!in_array($v,$mids0)){
						$mids2[] = $v;
					}
				}
				
				$sqlmap['id'] = array("IN",$mids2);
				$sqlmap['mobilestatus'] = 1;
			}elseif($_GET['status'] == 6){
				$mids = model('member_student')->where(array('class_id'=>array('gt',0),'end_time'=>array('gt',time())))->getField('mid',TRUE);				
				$sqlmap['id'] = array("IN",$mids);				
			}
		}
        $limit = (isset($_GET['limit']) && is_numeric($_GET['limit'])) ? $_GET['limit'] : 20;
        $lists = $this->service->get_lists($sqlmap,$_GET['page'],$limit);
        $count = $this->service->count($sqlmap);
        $pages = $this->admin_pages($count, $limit);
        $lists = array(
            'th' => array(
                'username' => array('title' => '家长及电话','length' => 24,'style' => 'member'),
				'lock' => array('length' => 8,'title' => '家长状态'),
                'source' => array('title' => '本人的来源','length' => 8,'style' => 'source'),
                'money' => array('length' => 15,'title' => '账户余额','style' => 'money'),
                'login' => array('title' => '注册&登录','length' => 20,'style' => 'login'),
                
            ),
            'lists' => $lists,
            'pages' => $pages,
        );
        $this->load->librarys('View')->assign('lists',$lists)->assign('pages',$pages)->display('member_index');
    }
	
	public function teacher() {
        $sqlmap = array();
        $sqlmap['username|email|mobile'] = array("LIKE", '%'.$_GET['keyword'].'%');
		if($_GET['status'] > 1){
			if($_GET['status'] < 4){
				$sqlmap['status'] = intval($_GET['status']);
			}else{
				$t_ids1 = $this->load->table('school/class')->getField('teacher1_id',TRUE);
				$t_ids2 = $this->load->table('school/class')->getField('teacher2_id',TRUE);
				$t_ids = array_merge($t_ids1,$t_ids2);
				if($_GET['status'] == 4){
					$sqlmap['id'] = array("NOT IN",$t_ids);
				}
				
				if($_GET['status'] == 5){
					$sqlmap['id'] = array("IN",$t_ids);
				}
			}
		}
        $sqlmap['group_id'] = 2;
        $limit = (isset($_GET['limit']) && is_numeric($_GET['limit'])) ? $_GET['limit'] : 20;
        $lists = $this->service->get_lists($sqlmap,$_GET['page'],$limit);
        $count = $this->service->count($sqlmap);
        $pages = $this->admin_pages($count, $limit);
		
		$t = mktime(0,0,0,date('m'),date('d')-date('w'),date('Y'));
		$start = mktime(0,0,0,date("m",$t),date("d",$t),date("Y",$t));
		$t = mktime(0,0,0,date('m'),date('d')+(6-date('w')),date('Y'));
		$end = mktime(23,59,59,date("m",$t),date("d",$t),date("Y",$t));

		foreach($lists as $k => $v){
			$fenshu = 0;
			$renshu = 0;
			foreach($v['class'] as $cv){
				$students = $this->load->table('member/member_student')->where(array("class_id"=>$cv['id'],'end_time'=>array('gt',time())))->select();
				foreach($students as $student){
					$point = $this->load->table('member/scoring')->where(array('teacher_id'=>$v['id'],'student_id'=>$student['id'],'type'=>1,'_string'=>'start_time = '.$start.' and end_time ='.$end))->find();
					if($point){
						$fenshu += $point['mealNum'];	
					}else{
						$fenshu += 3;	
					}
					$renshu++;
				}	
			}
			$lists[$k]['scoring'] = sprintf('%.1f',$fenshu/$renshu);
		}
		
        $lists = array(
            'th' => array(
                'username' => array('title' => '老师及电话','length' => 20,'style' => 'member'),
                'school_name' => array('title' => '学校名','length' => 10,'style' => 'level'),
				'class_name' => array('title' => '午托班','length' => 10),
				'status' => array('length' => 10,'title' => '老师状态','style' => 'status'),
				'scoring' => array('length' => 10,'title' => '当周评分','style' => 'scoring'),
                'login' => array('title' => '注册&登录','length' => 20,'style' => 'login'),
            ),
            'lists' => $lists,
            'pages' => $pages,
        );
        $this->load->librarys('View')->assign('lists',$lists)->assign('pages',$pages)->display('teacher_index');
    }
	
	public function principal() {
        $sqlmap = array();
        $sqlmap['username|email|mobile'] = array("LIKE", '%'.$_GET['keyword'].'%');
        $sqlmap['group_id'] = 3;
        $limit = (isset($_GET['limit']) && is_numeric($_GET['limit'])) ? $_GET['limit'] : 20;
        $lists = $this->service->get_lists($sqlmap,$_GET['page'],$limit);
        $count = $this->service->count($sqlmap);
        $pages = $this->admin_pages($count, $limit);
        $member_group = $this->load->service('member/member_group')->getfield('id,name');
        array_unshift($member_group,'所有等级');
        $lists = array(
            'th' => array(
                'username' => array('title' => '小昕及电话','length' => 25,'style' => 'member'),
                'lock' => array('length' => 20,'title' => '状态'),
				'login' => array('title' => '注册&登录','length' => 30,'style' => 'login'),
            ),
            'lists' => $lists,
            'pages' => $pages,
        );
        $this->load->librarys('View')->assign('lists',$lists)->assign('pages',$pages)->assign('member_group',$member_group)->display('principal_index');
    }
	
	public function student(){
		$sqlmap = array();
		$sqlmap['truename|area'] = array("LIKE", '%'.$_GET['keyword'].'%');
		if($_GET['mid'] >0){
			$sqlmap['mid'] = $_GET['mid'];
		}
		
		if($_GET['jkeyword']){
			$msql['username|truename|mobile'] = array("LIKE", '%'.$_GET['jkeyword'].'%');
			$mids = implode(",",$this->load->table('member/member')->where($msql)->getField('id',true));
			$sqlmap['mid'] = array("IN", $mids);
		}
		
		if($_GET['school_id'] >0){
			$sqlmap['school_id'] = $_GET['school_id'];
		}
		
		if($_GET['class_id'] >0){
			$sqlmap['class_id'] = $_GET['class_id'];
			$sqlmap['end_time'] = array("gt",time());
		}

		$limit = (isset($_GET['limit']) && is_numeric($_GET['limit'])) ? $_GET['limit'] : 20;
        $lists = $this->service_student->get_lists($sqlmap,$_GET['page'],$limit);
		
		$count = $this->service_student->count($sqlmap);
        $pages = $this->admin_pages($count, $limit);
		
		//var_dump($lists);
		//$this->service_student
		$lists = array(
            'th' => array(
                'truename' => array('title' => '孩子名字','length' => 7,'style' => 'member'),
                'parents' => array('title' => '家长及电话','length' => 8,'style' => 'parents'),
                'school_name' => array('length' => 13,'title' => '学校','style' => 'school_name'),
                'class_name' => array('title' => '午托班','length' => 8,'style' => 'class_name'),
                'roll' => array('length' => 5,'title' => '点名'),
				'grade' => array('length' => 11,'title' => '当日打分和点评'),
				'leaves' => array('length' => 7,'title' => '次日请假'),
				'classname' => array('length' => 5,'title' => '班级'),
				'teacher_name' => array('length' => 6,'title' => '班主任姓名'),
				'teacher_mobile' => array('length' => 10,'title' => '班主任电话'),
            ),
            'lists' => $lists,
            'pages' => $pages,
        );
		$schools = $this->load->service('school/school')->get_lists();
		$slists = $clists = array(0=>"请选择");
		foreach ($schools as $k => $v) {
			$slists[$v['id']] = $v['name'];
		}
		
		$class = $this->load->service('school/class')->get_lists();
		foreach ($class as $k => $v) {
			$clists[$v['id']] = $v['name'];
		}
        $this->load->librarys('View')->assign('lists',$lists)->assign('pages',$pages)->assign('slists',$slists)->assign('clists',$clists)->display('student_index');
	}
	
        public function tscore(){
            $sqlmap = array();
            $sqlmap['type'] = 1;
            if($_GET['id'] >0){
                    $sqlmap['teacher_id'] = $_GET['id'];
            }

            $limit = (isset($_GET['limit']) && is_numeric($_GET['limit'])) ? $_GET['limit'] : 20;
            $lists = $this->scoreService->get_lists($sqlmap,$_GET['page'],$limit);
			
			$count = $this->scoreService->count($sqlmap);
        	$pages = $this->admin_pages($count, $limit);
		
            //var_dump($lists);
            //$this->service_student
            $lists = array(
                'th' => array(
                    'student_name' => array('title' => '孩子名(家长名)','length' => 15,'style' => 'student_name'),
                    'teacher_name' => array('title' => '老师姓名','length' => 10),
                    'school_name' => array('length' => 15,'title' => '所在学校','style' => 'school_name'),
                    'class_name' => array('title' => '所在班级','length' => 15,'style' => 'class_name'),
                    'mealNum' => array('length' => 10,'title' => '评分'),
                    'time' => array('length' => 20,'title' => '评分时间段'),
                    'addtime' => array('length' => 15,'title' => '评分时间'),
                ),
                'lists' => $lists,
                'pages' => $pages,
            );
		
            $this->load->librarys('View')->assign('lists',$lists)->assign('pages',$pages)->display('tscore_index');
	}
        
	public function score(){
		$sqlmap = array();
		$sqlmap['type'] = 0;
		if($_GET['id'] >0){
			$sqlmap['student_id'] = $_GET['id'];
		}
		
		if($_GET['start']) {
            $time[] = array("GT", strtotime($_GET['start']));
        }
        if($_GET['end']) {
            $time[] = array("LT", strtotime($_GET['end']));
        }
		
		if($time){
            $sqlmap['addtime'] = $time;
        }
		
		if($_GET['cid']){
			$mids = implode(",",$this->load->table('member/member_student')->where(array('class_id'=>intval($_GET['cid'])))->getField('id',true));
			$sqlmap['student_id'] = array("IN", $mids);
		}
		
		$limit = (isset($_GET['limit']) && is_numeric($_GET['limit'])) ? $_GET['limit'] : 20;
        $lists = $this->scoreService->get_lists($sqlmap,$_GET['page'],$limit);
		$count = $this->scoreService->count($sqlmap);
        $pages = $this->admin_pages($count, $limit);
		
		//$this->service_student
		$lists = array(
            'th' => array(
                'class_name' => array('title' => '班级','length' => 8),
                'student_name' => array('title' => '姓名','length' => 10,'style' => 'student_name'),
                'mealNum' => array('length' => 8,'title' => '吃饭（1-5）','style' => 'mealNum'),
                'bedNum' => array('title' => '睡觉（1-5）','length' => 8,'style' => 'bedNum'),
                'noise' => array('length' => 5,'title' => '喧哗'),
				'chase' => array('length' => 5,'title' => '追赶'),
				'fight' => array('length' => 5,'title' => '打架'),
				'dirty' => array('length' => 5,'title' => '脏话'),
				'nottime' => array('length' => 8,'title' => '未准时到达'),
				'takeGoods' => array('length' => 8,'title' => '拿动他人物品'),
				'litter' => array('length' => 5,'title' => '乱扔垃圾'),
				'prank' => array('length' => 5,'title' => '恶作剧'),
				'other' => array('length' => 10,'title' => '其他可编辑'),
				'addtime' => array('length' => 10,'title' => '评分时间'),
            ),
            'lists' => $lists,
            'pages' => $pages,
        );
		
        $this->load->librarys('View')->assign('lists',$lists)->assign('pages',$pages)->display('score_index');
	}
	
	public function leave(){
		$sqlmap = array();
		$sqlmap['type'] = 1;
		if($_GET['id'] >0){
			$sqlmap['student_id'] = $_GET['id'];
		}
		
		$limit = (isset($_GET['limit']) && is_numeric($_GET['limit'])) ? $_GET['limit'] : 20;
		$lists = $this->pointService->get_lists($sqlmap,$_GET['page'],$limit);
		$count = $this->pointService->count($sqlmap);
		$pages = $this->admin_pages($count, $limit);
		//var_dump($lists);
		//die();
		$lists = array(
			'th' => array(
				'student_name' => array('title' => '孩子名(家长名)','length' => 25,'style' => 'student_name'),
				'school_name' => array('length' => 20,'title' => '所在学校','style' => 'school_name'),
				'class_name' => array('title' => '所在班级','length' => 20,'style' => 'class_name'),
				'pointTime' => array('length' => 15,'title' => '请假日期'),
				'addtime' => array('length' => 20,'title' => '发布时间'),
			),
			'lists' => $lists,
			'pages' => $pages,
		);
	
		$this->load->librarys('View')->assign('lists',$lists)->assign('pages',$pages)->display('leave_index');
	}
    
	public function student_delete() {
        if(empty($_GET['formhash']) || $_GET['formhash'] != FORMHASH) {
            showmessage('_token_error_',url('student'),0);
        }
        $result = $this->service_student->delete_by_id($_GET['ids']);
        showmessage('_operation_success_',url('student'),1);
    }
	
	public function student_edit() {
        $id = intval($_GET['id']);
        $member = $this->service_student->fetch_by_id($id);
        if (checksubmit('dosubmit')) {
            unset($_POST['dosubmit']);
            unset($_POST['formhash']);
            $data = $_POST;
            if(!empty($_FILES['head']['name'])) {
				$code = attachment_init(array('path' => 'member','mid' => 1,'allow_exts' => array('gif','jpg','jpeg','bmp','png')));
				$data['head'] = $this->attachment_service->setConfig($code)->upload('head');
				if(!$data['head']){
					showmessage($this->attachment_service->error);
				}
			}
            if (!$data['id'])
                unset($data['id']);
            
			$data['start_time'] = remove_xss(strtotime($data['start_time']));
			$data['end_time'] = remove_xss(strtotime($data['end_time']));
			$data['school_name'] = $this->load->table('school/school')->where(array('id'=>$data['school_id']))->getField('name');
			$data['class_name'] = $this->load->table('school/class')->where(array('id'=>$data['class_id']))->getField('name');
			$result = model('member/member_student')->update($data);
            if (!$result) {
                showmessage(model('member/member_student')->getError());
            }else{
				$this->attachment_service->attachment($data['head'], $member['head'],false);
				showmessage('_operation_success_', url('student'), 1);  
			}         
        } else {
			$schools = $this->load->service('school/school')->get_lists();
			$slists = $clists = array(0=>"请选择");
			foreach ($schools as $k => $v) {
				$slists[$v['id']] = $v['name'];
			}
			if($member['start_time'] == 0) $member['start_time'] = time();
			if($member['end_time'] == 0) $member['end_time'] = time();
			$class = $this->load->service('school/class')->get_lists();
			foreach ($class as $k => $v) {
				$clists[$v['id']] = $v['name'];
			}
            include $this->admin_tpl('student_edit');
        }
    }
	
	public function principal_add() {
        $group = model('member_group')->select();
		$group_id = 3;      
        include $this->admin_tpl('principal_edit');        
    }
	
	public function principal_edit() {
        $group = model('member_group')->select();
        $id = intval($_GET['id']);
        $member = $this->service->fetch_by_id($id);
		$group_id = $member['group_id'];
        if (checksubmit('dosubmit')) {
            unset($_POST['dosubmit']);
            unset($_POST['formhash']);
			if(!empty($_FILES['head']['name'])) {
				$code = attachment_init(array('path' => 'member','mid' => 1,'allow_exts' => array('gif','jpg','jpeg','bmp','png')));
				$_POST['head'] = $this->attachment_service->setConfig($code)->upload('head');
				if(!$_POST['head']){
					showmessage($this->attachment_service->error);
				}
			}
            $data = $_POST;
            if ($data['password'] == '') {
                unset($data['password']);
            } else {
                $data['encrypt'] = random(6);
                $data['password'] = md5(md5($data['password']) . $data['encrypt']);
            }
            if (!$data['id'])
                unset($data['id']);
            
			$result = model('member/member')->update($data);
            if (!$result) {
                showmessage(model('member/member')->getError());
            }
			$this->attachment_service->attachment($_POST['head'], $member['head'],false);
            showmessage('_operation_success_', url('principal'), 1);           
        } else {
            include $this->admin_tpl('principal_edit');
        }
    }
	
	public function teacher_add() {
        $group = model('member_group')->select();
		$group_id = 2;       
        include $this->admin_tpl('teacher_edit');        
    }
	
	public function teacher_edit() {
        $group = model('member_group')->select();
        $id = intval($_GET['id']);
        $member = $this->service->fetch_by_id($id);
		$group_id = $member['group_id'];
        if (checksubmit('dosubmit')) {
            unset($_POST['dosubmit']);
            unset($_POST['formhash']);
			if(!empty($_FILES['head']['name'])) {
				$code = attachment_init(array('path' => 'member','mid' => 1,'allow_exts' => array('gif','jpg','jpeg','bmp','png')));
				$_POST['head'] = $this->attachment_service->setConfig($code)->upload('head');
				if(!$_POST['head']){
					showmessage($this->attachment_service->error);
				}
			}
			
            $data = $_POST;
            if ($data['password'] == '') {
                unset($data['password']);
            } else {
                $data['encrypt'] = random(6);
                $data['password'] = md5(md5($data['password']) . $data['encrypt']);
            }
            if (!$data['id'])
                unset($data['id']);
            $result = model('member/member')->update($data);
            if (!$result) {
                showmessage(model('member/member')->getError());
            }
			$this->attachment_service->attachment($_POST['head'], $member['head'],false);
            showmessage('_operation_success_', url('teacher'), 1);           
        } else {
            include $this->admin_tpl('teacher_edit');
        }
    }
	
	public function add() {
        //查询会员全部会员等级
        $group = model('member_group')->select();
        $group_id = 1;
        include $this->admin_tpl('edit');
    }
	
	public function edit() {
        //查询会员全部会员等级
        $group = model('member_group')->select();
        $id = intval($_GET['id']);
        $member = $this->service->fetch_by_id($id);
        if (checksubmit('dosubmit')) {
            unset($_POST['dosubmit']);
            unset($_POST['formhash']);
            $data = $_POST;
            if ($data['password'] == '') {
                unset($data['password']);
            } else {
                $data['encrypt'] = random(6);
                $data['password'] = md5(md5($data['password']) . $data['encrypt']);
            }
            if (!$data['id'])
                unset($data['id']);
            $result = model('member/member')->update($data);
            if (!$result) {
                showmessage(model('member/member')->getError());
            }          
            showmessage('_operation_success_', url('index'), 1);           
        } else {
            include $this->admin_tpl('edit');
        }
    }

    public function delete() {
        if(empty($_GET['formhash']) || $_GET['formhash'] != FORMHASH) {
            showmessage('_token_error_',url('index'),0);
        }
        $result = $this->service->delete_by_id($_GET['ids']);
        showmessage('_operation_success_',url('index'),1);
    }

    public function address() {
        $_GET['mid'] = (int) $_GET['mid'];
        if((int) $_GET['has_address'] == 1){
            $limit = (isset($_GET['limit']) && is_numeric($_GET['limit'])) ? $_GET['limit'] : 5;
            $lists = $this->load->service('member/member_address')->lists(array('mid' => $_GET['mid']), $limit,$_GET['page']);
        }
        $pages = $this->admin_pages($lists['count'], $limit);
        $this->load->librarys('View')->assign('pages',$pages)->assign('lists',$lists)->display('member_address');
    }
	
	public function classes(){
		if (checksubmit('dosubmit')) {
			$ids = remove_xss($_GET['ids']);
			$school_id = intval($_GET['school_id']);
			$class_id = intval($_GET['class_id']);
			$data['school_id'] = $school_id;
			$data['school_name'] = $this->load->table('school/school')->where(array('id'=>$school_id))->getField('name');
			$data['class_id'] = $class_id;
			$data['class_name'] = $this->load->table('school/class')->where(array('id'=>$class_id))->getField('name');
			$result = $this->load->table('member/member_student')->where(array('id'=>array("IN",$ids)))->save($data);
			if (!$result) showmessage("分配班级失败");
			showmessage(lang('分配班级成功'),'',1,'json');
		}else{
			$schools = $this->load->service('school/school')->get_lists();
			$lists = $clists = array();
			foreach ($schools as $k => $v) {
				$lists[$v['id']] = $v['name'];
			}
			
			$class = $this->load->service('school/class')->get_lists();
			foreach ($class as $k => $v) {
				$school = $this->load->table('school/school')->find(array('id'=>$v['school_id']));
				$clists[$v['id']] = $v['name']."(".$school['name'].")";
			}
			
			$this->load->librarys('View')->assign('ids',$_GET['ids'])->assign('lists',$lists)->assign('clists',$clists)->display('alert_classes');
		}
	}
	
	public function tk(){
		$student = $this->load->table('member/member_student')->where(array('school_id'=>array('neq',0),'class_id'=>array('neq',0)))->select();
		
		foreach($student as $k => $v){
			$money = '+'.$v['school']['price'];			
			$field = "money";
			$msg = "系统自动退款";
			$mid = $v['mid'];
			$this->load->table('member')->where(array('id' => $mid))->setField($field, array("exp", $field.$money));
			$_member = $this->load->table('member')->setid($mid)->output();
			$log_info = array(
				'mid'      => $mid,
				'value'    => $money,
				'ltype'     => 1,
				'type'     => $field,
				'msg'      => $msg,
				'dateline' => TIMESTAMP,
				'admin_id' => (defined('IN_ADMIN')) ? ADMIN_ID : 0,
				'money_detail' => json_encode(array($field => sprintf('%.2f' ,$_member[$field])))
			);
			
			$this->load->table('member_log')->update($log_info);			
		}
		showmessage('_operation_success_',url('student'),1);
	}
	
	public function update() {
        $id = (int) $_GET['id'];
        $member = $this->service->fetch_by_id($id);
        if(!$member) showmessage($this->service->error);
        if(checksubmit('dosubmit')) {
            foreach ($_POST['info'] as $t => $v) {
                if(is_numeric($v['num']) && !empty($v['num'])) {
                    $v['num'] = ($v['action'] == 'inc') ? '+'.$v['num'] : '-'.$v['num'];
					$ltype = ($v['action'] == 'inc') ? 5 : 4;
                    $this->service->change_account1($id, $t, $v['num'], $_POST['msg'],$ltype);
                }
            }
            showmessage('_operation_success_', url('index'), 1);
        } else{
            $this->load->librarys('View')->assign('member',$member)->display('member_update');
        }
    }
}
